<template>
  <div class="ad-management-container">
    <!-- Echarts图表区域 -->
    <div class="chart-container">
      <div class="chart-tabs">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="广告种类分布" name="type"></el-tab-pane>
          <el-tab-pane label="商家广告数量" name="merchant"></el-tab-pane>
          <el-tab-pane label="广告效果分析" name="effect"></el-tab-pane>
        </el-tabs>
      </div>
      <div ref="chart" style="width: 100%; height: 400px;"></div>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="广告名称">
          <el-input v-model="searchForm.name" placeholder="请输入广告名称"></el-input>
        </el-form-item>
        <el-form-item label="广告类型">
          <el-select v-model="searchForm.type" placeholder="请选择广告类型">
            <el-option v-for="type in adTypes" :key="type.value" :label="type.label" :value="type.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" value="normal"></el-option>
            <el-option label="已停止" value="stopped"></el-option>
            <el-option label="已过期" value="expired"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.createTime"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">添加广告</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
        :data="adList"
        stripe
        border
        size="small"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="商品广告名称" min-width="150"></el-table-column>
        <el-table-column prop="type" label="广告类型" min-width="100">
          <template slot-scope="scope">
            {{ getTypeName(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="merchant" label="商家" min-width="120"></el-table-column>
        <el-table-column prop="description" label="描述" min-width="200"></el-table-column>
        <el-table-column prop="status" label="状态" min-width="80">
          <template slot-scope="scope">
            <el-tag 
              :type="scope.row.status === 'normal' ? 'success' : 
                    scope.row.status === 'stopped' ? 'info' : 'warning'">
              {{ scope.row.status === 'normal' ? '正常' : 
                 scope.row.status === 'stopped' ? '已停止' : '已过期' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" min-width="120"></el-table-column>
        <el-table-column prop="endDate" label="结束日期" min-width="120"></el-table-column>
        <el-table-column prop="participants" label="参与人数" min-width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160"></el-table-column>
        <el-table-column label="操作" min-width="250">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="mini" type="warning" @click="handleStop(scope.row)"
              :disabled="scope.row.status !== 'normal'">停止</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog :visible.sync="editDialogVisible" title="编辑广告">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="120px">
        <el-form-item label="广告名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="广告类型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择广告类型">
            <el-option v-for="type in adTypes" :key="type.value" :label="type.label" :value="type.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商家" prop="merchant">
          <el-input v-model="editForm.merchant"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="editForm.description" rows="4"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio label="normal">正常</el-radio>
            <el-radio label="stopped">已停止</el-radio>
            <el-radio label="expired">已过期</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="editForm.startDate"
            type="date"
            placeholder="选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="editForm.endDate"
            type="date"
            placeholder="选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="参与人数" prop="participants">
          <el-input v-model.number="editForm.participants"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import *as echarts from 'echarts';

export default {
  name: 'AdManagement',
  data() {
    return {
      activeTab: 'type',
      searchForm: {
        name: '',
        type: '',
        status: '',
        createTime: ''
      },
      adTypes: [
        { value: 'banner', label: '横幅广告' },
        { value: 'popup', label: '弹窗广告' },
        { value: 'video', label: '视频广告' },
        { value: 'carousel', label: '轮播广告' },
        { value: 'sidebar', label: '侧边栏广告' }
      ],
      adList: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      chartInstance: null,
      editDialogVisible: false,
      editForm: {
        id: '',
        name: '',
        type: 'banner',
        merchant: '',
        description: '',
        status: 'normal',
        startDate: '',
        endDate: '',
        participants: 0,
        createTime: ''
      },
      editRules: {
        name: [
          { required: true, message: '请输入广告名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择广告类型', trigger: 'change' }
        ],
        merchant: [
          { required: true, message: '请输入商家名称', trigger: 'blur' }
        ],
        startDate: [
          { required: true, message: '请选择开始日期', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择结束日期', trigger: 'change' }
        ]
      },
      multipleSelection: []
    };
  },
  mounted() {
    this.initChart();
    this.fetchData();
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
      this.chartInstance = null;
    }
  },
  methods: {
    // 初始化图表
    initChart() {
      this.chartInstance = echarts.init(this.$refs.chart);
      
      // 设置图表全局配置
      this.chartInstance.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          type: 'scroll',
          orient: 'horizontal',
          bottom: 10,
          data: []
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        }
      });
      
      // 监听窗口大小变化，调整图表尺寸
      window.addEventListener('resize', () => {
        if (this.chartInstance) {
          this.chartInstance.resize();
        }
      });
      
      // 初始化显示第一个图表
      this.updateChart();
    },
    
    // 更新图表数据
    updateChart() {
      if (!this.chartInstance) return;
      
      let option;
      
      // 根据当前激活的标签页，生成不同的图表配置
      switch (this.activeTab) {
        case 'type':
          option = this.getTypeDistributionChart();
          break;
        case 'merchant':
          option = this.getMerchantChart();
          break;
        case 'effect':
          option = this.getEffectChart();
          break;
        default:
          option = this.getTypeDistributionChart();
      }
      
      this.chartInstance.setOption(option);
    },
    
    // 获取广告种类分布图表配置
    getTypeDistributionChart() {
      // 统计每种类型的广告数量
      const typeCount = {};
      this.adTypes.forEach(type => {
        typeCount[type.value] = 0;
      });
      
      this.adList.forEach(ad => {
        if (typeCount[ad.type] !== undefined) {
          typeCount[ad.type]++;
        }
      });
      
      const data = this.adTypes.map(type => ({
        value: typeCount[type.value],
        name: type.label
      }));
      
      return {
        title: {
          text: '广告种类分布',
          left: 'center'
        },
        series: [
          {
            name: '广告数量',
            type: 'pie',
            radius: '55%',
            center: ['50%', '45%'],
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
    },
    
    // 获取商家广告数量图表配置
    getMerchantChart() {
      // 统计每个商家的广告数量
      const merchantCount = {};
      this.adList.forEach(ad => {
        if (merchantCount[ad.merchant]) {
          merchantCount[ad.merchant]++;
        } else {
          merchantCount[ad.merchant] = 1;
        }
      });
      
      const data = Object.keys(merchantCount).map(merchant => ({
        value: merchantCount[merchant],
        name: merchant
      }));
      
      return {
        title: {
          text: '商家广告数量',
          left: 'center'
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.name)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '广告数量',
            type: 'bar',
            data: data.map(item => item.value)
          }
        ]
      };
    },
    
    // 获取广告效果分析图表配置
    getEffectChart() {
      // 按广告类型统计参与人数
      const typeParticipants = {};
      this.adTypes.forEach(type => {
        typeParticipants[type.value] = 0;
      });
      
      this.adList.forEach(ad => {
        if (typeParticipants[ad.type] !== undefined) {
          typeParticipants[ad.type] += ad.participants;
        }
      });
      
      const data = this.adTypes.map(type => ({
        value: typeParticipants[type.value],
        name: type.label
      }));
      
      return {
        title: {
          text: '广告效果分析',
          left: 'center'
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.name)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '参与人数',
            type: 'line',
            data: data.map(item => item.value)
          }
        ]
      };
    },
    
    // 获取广告类型名称
    getTypeName(typeValue) {
      const type = this.adTypes.find(t => t.value === typeValue);
      return type ? type.label : '未知类型';
    },
    
    // 获取数据
    fetchData() {
      // 模拟API请求
      const mockData = [
        { id: 1, name: '夏日促销活动', type: 'banner', merchant: '佳惠超市', description: '夏季清凉商品大促销', status: 'normal', startDate: '2025-05-01', endDate: '2025-05-31', participants: 1200, createTime: '2025-05-01' },
        { id: 2, name: '会员专享折扣', type: 'popup', merchant: '永辉超市', description: '会员专享85折优惠', status: 'normal', startDate: '2025-05-05', endDate: '2025-05-25', participants: 850, createTime: '2025-05-05' },
        { id: 3, name: '新品上市', type: 'video', merchant: '沃尔玛', description: '全新进口水果系列', status: 'normal', startDate: '2025-05-10', endDate: '2025-06-10', participants: 980, createTime: '2025-05-10' },
        { id: 4, name: '周末特惠', type: 'carousel', merchant: '家乐福', description: '周末家庭购物满减活动', status: 'stopped', startDate: '2025-04-15', endDate: '2025-04-30', participants: 1500, createTime: '2025-04-15' },
        { id: 5, name: '节日礼盒', type: 'sidebar', merchant: '大润发', description: '端午特色礼品套装', status: 'normal', startDate: '2025-05-20', endDate: '2025-06-05', participants: 720, createTime: '2025-05-20' },
        { id: 6, name: '家电促销', type: 'banner', merchant: '苏宁易购', description: '夏季家电清凉价', status: 'normal', startDate: '2025-05-18', endDate: '2025-06-18', participants: 1100, createTime: '2025-05-18' },
        { id: 7, name: '生鲜特惠', type: 'popup', merchant: '永辉超市', description: '新鲜水果限时折扣', status: 'expired', startDate: '2025-04-25', endDate: '2025-05-10', participants: 950, createTime: '2025-04-25' },
        { id: 8, name: '儿童专区', type: 'video', merchant: '沃尔玛', description: '童装玩具特惠活动', status: 'normal', startDate: '2025-05-22', endDate: '2025-06-22', participants: 680, createTime: '2025-05-22' },
        { id: 9, name: '美妆专区', type: 'carousel', merchant: '屈臣氏', description: '夏季美妆大促销', status: 'normal', startDate: '2025-05-15', endDate: '2025-06-15', participants: 820, createTime: '2025-05-15' },
        { id: 10, name: '家居用品', type: 'sidebar', merchant: '宜家家居', description: '家居用品满减活动', status: 'normal', startDate: '2025-05-08', endDate: '2025-06-08', participants: 760, createTime: '2025-05-08' }
      ];
      
      // 模拟搜索过滤
      let filteredData = mockData.filter(item => {
        return (
          (!this.searchForm.name || item.name.includes(this.searchForm.name)) &&
          (!this.searchForm.type || item.type === this.searchForm.type) &&
          (!this.searchForm.status || item.status === this.searchForm.status) &&
          (!this.searchForm.createTime || item.createTime === this.searchForm.createTime)
        );
      });
      
      this.total = filteredData.length;
      
      // 模拟分页
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.adList = filteredData.slice(start, end);
      
      // 更新图表数据
      this.updateChart();
    },
    
    // 标签页切换处理
    handleTabClick(tab) {
      this.activeTab = tab.name;
      this.updateChart();
    },
    
    // 搜索按钮处理
    handleSearch() {
      this.currentPage = 1;
      this.fetchData();
    },
    
    // 重置按钮处理
    handleReset() {
      this.searchForm = {
        name: '',
        type: '',
        status: '',
        createTime: ''
      };
      this.currentPage = 1;
      this.fetchData();
    },
    
    // 添加广告按钮处理
    handleAdd() {
      this.editForm = {
        id: '',
        name: '',
        type: 'banner',
        merchant: '',
        description: '',
        status: 'normal',
        startDate: '',
        endDate: '',
        participants: 0,
        createTime: new Date().toISOString().split('T')[0]
      };
      this.editDialogVisible = true;
    },
    
    // 分页大小变化处理
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    
    // 当前页码变化处理
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    
    // 多选框变化处理
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    
    // 编辑按钮处理
    handleEdit(row) {
      this.editForm = { ...row };
      this.editDialogVisible = true;
    },
    
    // 删除按钮处理
    handleDelete(row) {
      this.$confirm('确定要删除此广告吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟删除操作
        this.adList = this.adList.filter(item => item.id !== row.id);
        this.total = this.total - 1;
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        // 取消操作
      });
    },
    
    // 停止按钮处理
    handleStop(row) {
      this.$confirm('确定要停止此广告吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟停止操作
        const index = this.adList.findIndex(item => item.id === row.id);
        if (index !== -1) {
          this.adList[index].status = 'stopped';
        }
        this.$message({
          type: 'success',
          message: '广告已停止!'
        });
      }).catch(() => {
        // 取消操作
      });
    },
    
    // 保存编辑处理
    handleSave() {
      // 表单验证
      this.$refs.editForm.validate(valid => {
        if (valid) {
          // 检查日期逻辑
          if (this.editForm.startDate && this.editForm.endDate && 
              new Date(this.editForm.startDate) > new Date(this.editForm.endDate)) {
            this.$message.error('开始日期不能晚于结束日期');
            return;
          }
          
          // 模拟保存操作
          if (this.editForm.id) {
            // 更新现有广告
            const index = this.adList.findIndex(item => item.id === this.editForm.id);
            if (index !== -1) {
              this.adList.splice(index, 1, this.editForm);
            }
          } else {
            // 添加新广告
            this.editForm.id = Date.now();
            this.adList.unshift(this.editForm);
            this.total = this.total + 1;
          }
          
          this.editDialogVisible = false;
          this.$message({
            type: 'success',
            message: '保存成功!'
          });
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.ad-management-container {
  padding: 20px;
}

.chart-container {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.search-area {
  margin-bottom: 20px;
}

.table-container {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>  